package com.feinno.urcs.group.http.util;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created by wuzhiguo on 15-5-12.
 */
public class HttpHelper {

    public static byte[] getRequestBody(HttpServletRequest request) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int contentLength = request.getContentLength();
        if (contentLength > 0) {
            int sum = 0;
            byte[] buffer = new byte[contentLength];
            while (sum < contentLength) {
                int count = request.getInputStream().read(buffer);
                if (count > 0) {
                    outputStream.write(buffer, 0, count);
                    sum += count;
                } else if (count < 0) {
                    outputStream.close();
                    throw new IOException(String.format("getRequestBody read return %s. contentLength:%s sum:%s ",
                            count, contentLength, sum));
                }
            }
        }

        outputStream.flush();
        byte[] outputBuffer = outputStream.toByteArray();
        outputStream.close();
        return outputBuffer;
    }

    public static String getRequestString(HttpServletRequest request, String body) {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("%s %s %s\n", request.getMethod(), request.getRequestURI(), request.getProtocol()));
        for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
            String headName = e.nextElement();
            String headValue = request.getHeader(headName);
            sb.append(String.format("%s: %s\n", headName, headValue));
        }
        if (body != null && body.length() > 0) {
            sb.append("\n");
            sb.append(body);
        }

        return sb.toString();
    }

    public static String getRequestString(HttpServletRequest request) {
        return getRequestString(request, null);
    }

}
